<template>
  <div>
    <el-card :bordered="false" shadow="never" class="mt16">
      <el-form :model="formData" label-width="160px">
        <el-form-item label="商家名称：">
          <el-input
            v-model="formData.name"
            :maxlength="30"
            placeholder="请输入商家名称"
            class="content_width"
          ></el-input>
        </el-form-item>

        <el-form-item label="联系人名称：">
          <el-input
            v-model="formData.nickname"
            placeholder="请输入联系人名称"
            class="content_width"
          ></el-input>
        </el-form-item>

        <el-form-item label="联系电话：">
          <el-input
            v-model="formData.mobile"
            placeholder="请输入联系电话"
            class="content_width"
          ></el-input>
        </el-form-item>
        <el-form-item label="涉及项目：">
          <el-input
            v-model="formData.relates_to_item"
            placeholder="请输入涉及项目"
            class="content_width"
          ></el-input>
        </el-form-item>

        <el-form-item label="门诊简介：">
          <el-input
            type="textarea"
            :rows="2"
            v-model="formData.intro"
            placeholder="请输入门诊简介"
            class="content_width"
          ></el-input>
        </el-form-item>


        <div class="item-box">
          <el-form-item label="支付宝账号：">
            <el-input
              v-model="formData.aly_account"
              :maxlength="30"
              placeholder="请输入支付宝账号"
              class="content_width"
            ></el-input>
          </el-form-item>
          <el-form-item label="支付宝账号名称：">
            <el-input
              v-model="formData.aly_name"
              :maxlength="30"
              placeholder="请输入支付宝账号名称"
              class="content_width"
            ></el-input>
          </el-form-item>
        </div>

        <div class="item-box">
          <el-form-item label="营业时间：">
<!--            <el-input-->
<!--              v-model="formData.run_start_time"-->
<!--              :maxlength="30"-->
<!--              placeholder="请输入营业时间"-->
<!--              class="content_width"-->
<!--            ></el-input>-->
            <el-time-select
              v-model="formData.run_start_time"
              class="content_width"
              :picker-options="{start: '08:00',step: '00:30',end: '19:00'}"
              placeholder="选择时间">
            </el-time-select>
          </el-form-item>
          <el-form-item label="营业结束时间：">
            <!--            <el-input-->
            <!--              v-model="formData.run_end_time"-->
            <!--              :maxlength="30"-->
            <!--              placeholder="请输入营业结束时间"-->
            <!--              class="content_width"-->
            <!--            ></el-input>-->
            <el-time-select
              v-model="formData.run_end_time"
              class="content_width"
              :picker-options="{start: '08:00',step: '00:30',end: '19:00'}"
              placeholder="选择时间">
            </el-time-select>
          </el-form-item>
        </div>

        <div class="item-box">
          <el-form-item label="商家钱包(可提现)：">
            <template>
              <div class="content_width">{{ formData.wallet }} 元</div>
            </template>
          </el-form-item>
          <el-form-item label="编码：">
            <template>
              <div class="content_width">{{ formData.serial_number ? formData.serial_number : "暂无" }}</div>
            </template>
          </el-form-item>
        </div>

        <el-form-item class="form" label="商家LOGO：">
          <div class="picBox">
            <div class="pictrue" v-if="formData.logo" v-viewer>
              <img v-lazy="formData.logo" />
              <i class="el-icon-error btndel" @click="logoRemove(0)"></i>
            </div>
            <div v-else class="upLoad acea-row row-center-wrapper" @click="modalPicTap('单选',0)">
              <i class="el-icon-plus" style="font-size: 24px"></i>
            </div>
          </div>
        </el-form-item>
        <div class="item-img">
          <el-form-item class="form" label="营业执照：" style="flex: 1">
            <div class="acea-row">
              <template v-if="formData.business_license">
                <div class="pictrue" style="margin-bottom: 5px" v-for="(item, index) in formData.business_license"
                     :key="index" draggable="true" v-viewer>
                  <img v-lazy="item" />
                  <i class="el-icon-error btndel" @click="handleRemove(index,1)"></i>
                </div>
              </template>
              <div class="upLoad acea-row row-center-wrapper" style="margin-bottom: 5px"
                   @click="modalPicTap('多选',1)" v-if="formData.business_license.length < 2">
                <i class="el-icon-plus" style="font-size: 24px"></i>
              </div>
            </div>
            <div class="tip">营业执照正反面</div>
          </el-form-item>
          <el-form-item class="form" label="其他资质：" style="flex: 1">
            <div class="acea-row">
              <template v-if="formData.other_qualifications">
                <div class="pictrue" style="margin-bottom: 5px" v-for="(item, index) in formData.other_qualifications"
                     :key="index" draggable="true" v-viewer>
                  <img v-lazy="item" />
                  <i class="el-icon-error btndel" @click="handleRemove(index,2)"></i>
                </div>
              </template>
              <div class="upLoad acea-row row-center-wrapper" style="margin-bottom: 5px"
                   @click="modalPicTap('多选',2)" v-if="formData.other_qualifications.length < 5">
                <i class="el-icon-plus" style="font-size: 24px"></i>
              </div>
            </div>
            <div class="tip">最多上传5张图片</div>
          </el-form-item>
        </div>

        <div class="item-img">
          <el-form-item class="form" label="环境图片：" style="flex: 1">
            <div class="acea-row">
              <template v-if="formData.environment_img">
                <div class="pictrue" style="margin-bottom: 5px" v-for="(item, index) in formData.environment_img"
                     :key="index" draggable="true" v-viewer>
                  <img v-lazy="item" />
                  <i class="el-icon-error btndel" @click="handleRemove(index,3)"></i>
                </div>
              </template>
              <div class="upLoad acea-row row-center-wrapper" style="margin-bottom: 5px"
                   @click="modalPicTap('多选',3)" v-if="formData.environment_img.length < 5">
                <i class="el-icon-plus" style="font-size: 24px"></i>
              </div>
            </div>
            <div class="tip">最多上传5张图片</div>
          </el-form-item>
          <el-form-item class="form" label="团队图片：" style="flex: 1">
            <div class="picBox">
              <div class="pictrue" v-if="formData.team_img" v-viewer>
                <img v-lazy="formData.team_img" />
                <i class="el-icon-error btndel" @click="logoRemove(1)"></i>
              </div>
              <div v-else class="upLoad acea-row row-center-wrapper" @click="modalPicTap('单选',4)">
                <i class="el-icon-plus" style="font-size: 24px"></i>
              </div>
            </div>
          </el-form-item>
        </div>
        <el-form-item class="form" label="门店二维码：">
          <div class="pictrue" v-if="formData.qr_code" v-viewer>
            <img v-lazy="formData.qr_code" />
          </div>
        </el-form-item>

        <el-form-item label="营业状态：">
          <el-radio-group v-model="formData.is_run">
            <el-radio :label="1">营业中</el-radio>
            <el-radio :label="0">暂停营业</el-radio>
          </el-radio-group>
        </el-form-item>


        <el-form-item label="地址：">
          <el-cascader
            :options="addressData"
            v-model="addressModel"
            @change="handleChange"
            ref="groupList"
            style="width: 405px"
          ></el-cascader>
        </el-form-item>


        <div class="item-box">
          <el-form-item label="详细地址：">
            <el-input
              type="textarea"
              :rows="2"
              v-model="formData.address"
              placeholder="请输入详细地址"
              class="content_width"
            ></el-input>
          </el-form-item>
          <el-button type="primary" class="el-but" id="search" @click="initAutoComplete">搜索</el-button>
        </div>
        <!-- 地图容器 -->
        <div id="mapContainer" style="width: 800px; height: 400px;"></div>
        <el-form-item>
          <el-button type="primary" @click="save" :disabled="disabled">编辑</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-dialog z-index="20" :visible.sync="modalPic" width="950px" title="上传分类图" :close-on-click-modal="false">
      <uploadPictures
        :isChoice="isChoice"
        @getPic="getPic"
        @getPicD="getPicD"
        :gridBtn="gridBtn"
        :gridPic="gridPic"
        v-if="modalPic"
      ></uploadPictures>
    </el-dialog>

  </div>
</template>


<script>
import { mapState } from "vuex";
import uploadPictures from "@/components/uploadPictures";
import AMapLoader from "@amap/amap-jsapi-loader";
import { cityList } from "@/api/app";
import { merchantDetailsApi, merchantEditApi } from "@/api/setting";

import axios from "axios";

let marker;
export default {
  name: "storeCouponCreate",
  components: {
    // goodsList,
    uploadPictures
  },
  data() {
    return {
      disabled: false,
      map: null,
      marker: null,
      // marker: '', //  Marker实例
      geocoder: null,
      infoWindow: null,
      addressFValue: "", // 省市区id和地址
      addressData: [],  //  省市区列表
      addressModel: [],  //  绑定省市区id值
      longitude: "", //  经度
      latitude: "", //纬度
      formData: {
        name: "",  //  商家名称
        nickname: "",  //  联系人名称
        mobile: "",  //  联系电话
        logo: "",  //  商家LOGO
        wallet: 0,  //  商家钱包(可提现)
        serial_number: "",  //  编码
        aly_account: "",  //  支付宝账号
        aly_name: "",  //  支付宝账号名称
        qr_code: "",  //  门店二维码
        relates_to_item: "",  //  涉及项目
        intro: "",  //  门诊简介
        address: null,  //  详细地址
        province_id: null,  //  省ID
        city_id: null,  //  市ID
        district_id: null,  //  区ID
        longitude: '',  //  经度
        latitude: '',  //  纬度
        business_license: [],  //  营业执照
        other_qualifications: [],  //  其他资质
        environment_img: [],  //  环境图片
        team_img: null,  //  团队图片
        run_start_time: "",  //  营业时间
        run_end_time: "",  //  营业结束时间
        is_run: 1  //  营业状态[0=暂停营业, 1=营业中]
      },
      typeImg: 0,  //  决定图片上传类型
      imgDelete: 0,
      isChoice: "",
      modalPic: false,
      modals: false,
      gridPic: {
        xl: 6,
        lg: 8,
        md: 12,
        sm: 12,
        xs: 12
      },
      gridBtn: {
        xl: 4,
        lg: 8,
        md: 8,
        sm: 8,
        xs: 8
      },
      images: []

    };
  },
  computed: {
    ...mapState("media", ["isMobile"]),
    isEdit() {
      return !!this.$route.params.edit;
    }
  },
  created() {
    // this.getCategoryList();
    this.getCityList();
    this.getMerchantDetails();
    // if (this.$route.params.id) {
    //   this.formData.id = (this.isEdit && Number(this.$route.params.id)) || 0;
    //   this.getCouponDetail();
    // }
  },
  mounted() {
    //  初始化地图

  },
  methods: {
    // 编辑
    save() {
      console.log(this.formData,'编辑1111');
        if(!this.formData.name)return this.$message.error('请输入商家名称');
      merchantEditApi(this.formData).then((res)=>{
        if(res.status === 200){
         this.$message.success('编辑成功')
          this.getMerchantDetails()
        }
        console.log(res,'编辑成功');
      })
    },
    // 选择图片
    modalPicTap(type, index) {
      this.isChoice = type;
      switch (index) {
        case 0:
          this.typeImg = 0;
          break;
        case 1:
          this.typeImg = 1;
          break;
        case 2:
          this.typeImg = 2;
          break;
        case 3:
          this.typeImg = 3;
          break;
        case 4:
          this.typeImg = 4;
          break;
      }
      this.modalPic = true;
    },
    // 选中单张图片
    getPic(pc) {
      if (this.typeImg === 0) {
        this.formData.logo = pc.att_dir;
      } else if (this.typeImg === 4) {
        this.formData.team_img = pc.att_dir;
      }
      this.modalPic = false;
    },
    // 获取多张图信息
    getPicD(pc) {
      this.images = pc;
      this.images.map((item) => {
        if (this.typeImg === 1) {
          this.formData.business_license.push(item.att_dir);
          this.formData.business_license = this.formData.business_license.splice(0, 2);
        } else if (this.typeImg === 2) {
          this.formData.other_qualifications.push(item.att_dir);
          this.formData.other_qualifications = this.formData.other_qualifications.splice(0, 5);
        } else if (this.typeImg === 3) {
          this.formData.environment_img.push(item.att_dir);
          this.formData.environment_img = this.formData.environment_img.splice(0, 5);
        } else if (this.typeImg === 4) {
          this.formData.team_img.push(item.att_dir);
          this.formData.team_img = this.formData.team_img.splice(0, 5);
        }

      });
      this.modalPic = false;
    },
    // 获取省市区
    getCityList() {
      cityList().then((res) => {
        // res.data.map((item) => {
        //   item.value = item.label;
        //   if (item.children && item.children.length) {
        //     item.children.map((j) => {
        //       j.value = j.label;
        //       if (j.children && j.children.length) {
        //         j.children.map((o) => {
        //           o.value = o.label;
        //         });
        //       }
        //     });
        //   }
        // });
        this.addressData = res.data;
      });
    },
    // 获取商户详情
    getMerchantDetails() {
      merchantDetailsApi().then((res) => {
        this.formData = res.data;
        this.addressModel=[this.formData.province_id,this.formData.city_id,this.formData.district_id]
        // console.log( this.formData,'下去啊');
        this.loadMap();
      });
    },
    // 选择地址
    handleChange(value) {
      if (value) {
        this.formData.province_id = value[0];
        this.formData.city_id = value[1];
        this.formData.district_id = value[2];
        let address = this.$refs["groupList"].getCheckedNodes();
        this.addressFValue = address[0].pathLabels[0] + address[0].pathLabels[1] + address[0].pathLabels[2];
        // console.log("选择地址", this.addressFValue);
      }

    },
    //  删除轮播图列表的某一个元素
    handleRemove(i, index) {
      if (index === 1) {
        this.formData.business_license.splice(i, 1);
      } else if (index === 2) {
        this.formData.other_qualifications.splice(i, 1);
      } else if (index === 3) {
        this.formData.environment_img.splice(i, 1);
      } else if (index === 4) {
        this.formData.team_img.splice(i, 1);
      }
    },

    // 删除logoOr团队图片
    logoRemove(e) {
      if (e === 0) {
        this.formData.logo = "";
      } else {
        this.formData.team_img = "";
      }
    },
    async loadMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "bedf972a39997a12c5899f2f9cbca376"
      };
      await AMapLoader.load({
        key: "30ea57ad50b5fd5346d389ee6cfdf10f", // 替换为你的 API Key
        version: "2.0",
        plugins: ["AMap.Marker", "AMap.InfoWindow", "AMap.PlaceSearch"], // 添加 PlaceSearch 插件
        callback: "onAPILoaded" // 回调函数
      });
      // console.log('地图加载完成',document.getElementById('mapContainer'));
      this.map = new AMap.Map("mapContainer", {
        center: [this.formData.longitude || 116.397428, this.formData.latitude || 39.90923], // 初始中心点
        zoom: 13,
        resizeEnable: true,
        viewMode: "2D" //默认使用 2D 模式
      });

      this.addMarker(); // 添加标记点的方法
    },

    addMarker() {
      this.marker = new window.AMap.Marker({
        position: [120.230349, 30.228173]
      });
      this.marker.setMap(this.map);

      this.infoWindow = new window.AMap.InfoWindow({
        content: "奥体中心",
        offset: new window.AMap.Pixel(0, -30)
      });
      this.marker.on("click", () => {
        this.infoWindow.open(this.map, this.marker.getPosition());
      });
    },

    initAutoComplete() {
      // if (!this.addressFValue) return alert("请输入地址");
      // if (!this.formData.address) return alert("请输入详细地址");
      const placeSearch = new window.AMap.PlaceSearch({ // 创建地点搜索实例
        map: this.map
      });
      const addressData = this.addressFValue + this.formData.address;
      placeSearch.search(addressData, (status, result) => {
        if (status === "complete" && result.info === "OK") {
          // 搜索成功
          this.map.setCenter(result.poiList.pois[0].location); // 将地图中心移动到第一个结果
          this.addSearchMarker(result.poiList.pois[0].location); // 添加搜索结果标记
          this.formData.longitude = result.poiList.pois[0].location.lng;
          this.formData.latitude = result.poiList.pois[0].location.lat;
          console.log(this.formData);
        } else {
          console.error("搜索失败:");
        }
      });
      this.map.on("click", (e) => {
        console.log(e, "进度纬度");
      });
    },

    addSearchMarker(location) {
      if (this.marker) {
        this.marker.setMap(null); // 移除旧标记
      }
      this.marker = new window.AMap.Marker({
        position: location // 使用搜索到的地址位置
      });
      this.marker.setMap(this.map); // 将新标记添加到地图
    },

    onAPILoaded() {
      this.loaded = true;
      console.log("地图加载完成，可以执行其他操作");
    }
  }
};
</script>

<style scoped lang="scss">
#mapContainer {
  margin: 0 0 20px 150px;
}

.item-box {
  display: flex;
}

.el-but {
  margin-left: 40px;
  height: 40px;
}

.item-img {
  display: flex;
  width: 70%;
}

.content_width {
  width: 405px;
}

.info {
  color: #888;
  font-size: 12px;
}

.pictrue {
  width: 60px;
  height: 60px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  margin-right: 15px;
  display: inline-block;
  position: relative;
  cursor: pointer;

  img {
    width: 100%;
    height: 100%;
  }

  .btndel {
    position: absolute;
    z-index: 1;
    width: 20px !important;
    height: 20px !important;
    left: 45px;
    top: 0;
  }
}

.upLoad {
  width: 58px;
  height: 58px;
  line-height: 58px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  background: rgba(0, 0, 0, 0.02);
  cursor: pointer;
}

.ivu-icon-ios-close-circle {
  position: absolute;
  top: 0;
  right: 0;
  transform: translate(50%, -50%);
}

.tip {
  color: #888;
  font-size: 12px;
  line-height: 16px;
}
</style>
